import { Injectable } from '@angular/core';
import { ActivatedRoute, Router, NavigationEnd } from '@angular/router';
import { filter, map, startWith } from 'rxjs/operators';
import { BehaviorSubject } from 'rxjs';
import { ProfileService } from 'app/services/profile.service';

@Injectable({
	providedIn: 'root',
})
export class SubheaderService {
	public header$ = this.router.events.pipe(
		filter(event => event instanceof NavigationEnd),
		startWith(null),
		map(() => this.getSubheader()),
	);
	public title$ = new BehaviorSubject<string>('');
	constructor(private route: ActivatedRoute, private router: Router, private profileService: ProfileService) { }

	private getSubheader() {
		const heads: SubHeader[] = [];
		try {
			let path = '';
			for (let route = this.route; route; route = route.firstChild) {
				const config = route.routeConfig;
				if (!config) {
					continue;
				}
				if (config.path) {
					path += '/' + config.path;
				}
				if (config.data && config.data.title) {
					heads.push({ title: config.data.title, path: path });
				}
			}
			const currentTitle = heads[heads.length - 1].title;
			this.profileService.profile$.then(profile => {
				document.title = `${currentTitle} | ${profile.name}`;
			});
			this.title$.next(currentTitle);
		} catch (e) {

		}

		return heads;
	}
}

interface SubHeader {
	title: string;
	path: string;
}
